import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Field, Form } from '@teamix/ui';
import { getOrgCrypto, getRepoCrypto, updateRepoCrypto } from 'api/index.js';
import CryptoSwitch from './cryptoSwitch';
import './index.scss';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

export default class BaseForm extends Component {
  static propTypes = {
    setDeleteBtnDisableByCrypto: PropTypes.func,
  };

  static defaultProps = {
    setDeleteBtnDisableByCrypto: () => {},
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      orgCryptoInfo: {},
      repoCryptoInfo: {},
    };
  }

  componentDidMount() {
    this.initData();
  }

  initData = () => {
    this.setState({
      isLoadingCrypto: true,
    });

    Promise.all([getOrgCrypto(), getRepoCrypto()])
      .then((result) => {
        const [orgCryptoInfo, repoCryptoInfo] = result;
        this.setState({
          orgCryptoInfo,
          repoCryptoInfo,
          isLoadingCrypto: false,
        });

        this.props.setDeleteBtnDisableByCrypto(repoCryptoInfo.is_enabled);
      })
      .catch((err) => {
        console.error(err);
        this.setState({
          isLoadingCrypto: false,
        });
      });
  };

  onToggleCrypto = () => {
    const { repoCryptoInfo } = this.state;
    this.setState({
      isToggleCrypto: true,
    });

    updateRepoCrypto({
      is_enabled: !repoCryptoInfo.is_enabled,
    })
      .then(() => {
        this.setState({
          isToggleCrypto: false,
          repoCryptoInfo: {
            ...repoCryptoInfo,
            is_enabled: !repoCryptoInfo.is_enabled,
          },
        });

        this.props.setDeleteBtnDisableByCrypto(!repoCryptoInfo.is_enabled);
      })
      .catch(() => {
        this.setState({
          isToggleCrypto: false,
        });
      });
  };

  render() {
    const { orgCryptoInfo, repoCryptoInfo, isLoadingCrypto, isToggleCrypto } = this.state;

    return (
      <Form {...formItemLayout} field={this.field} labelAlign="top">
        <FormItem label="" style={{ marginBottom: 0 }}>
          <CryptoSwitch
            {...{
              orgCryptoInfo,
              repoCryptoInfo,
              isLoadingCrypto,
              isToggleCrypto,
              onToggleCrypto: this.onToggleCrypto,
            }}
          />
        </FormItem>
      </Form>
    );
  }
}
